'use client'; import { useEffect, useRef, useState, useTransition } from 'react'; import { useRouter } from 'next/navigation'; import { OPENAI_IMAGE_MODEL, resolveImageModel, SUPPORTED_MODELS, type ImageModel } from '@/app/lib/image-models'; import { FramedPreview } from '@/app/components/FramedPreview'; import type { FrameId } from '@/app/data/frames'; import { sizeLabel, type ProductId, type Orientation } from '@/app/lib/pricing'; import { OrderConversation } from '@/app/components/OrderConversation'; import { OrderMessageTime } from '@/app/components/OrderMessageTime'; import { ORDER_MESSAGE_LIMIT, PROOF_PUBLISH_STATUSES, STUDIO_MESSAGE_STATUSES, type activeProofRevision, type orderMessageConfig, type OrderMessage } from '@/app/lib/order-messages'; type Generation = { id: string; model: string; prompt: string; cleanUrl: string; published: boolean; /** Set by /api/orders/[id]/revise when the customer asks for changes * on the generation that was current at that moment. Used to label * prior generations in the History panel. Null = never rejected. */ rejectedAt: string | null; createdAt: string; }; type FrameConfig = { productId: ProductId; size: string; orientation: Orientation; frame: FrameId; matteId: string | null; }; type MessagePurpose = 'proof' | 'message'; function GenerationSpinner({ large = false }: { large?: boolean }) { return ( ); } type Props = { orderId: string; status: string; currentProofId: string | null; proofRevision: ReturnType; sentRevisions: ReturnType['sentRevisions']; pendingFeedback: string; petPhotoUrls: string[]; customStyleUrl: string | null; /** Cached GPT-4o Vision description of the customer's style ref. * Null when admin hasn't clicked Analyze yet. When present, the * initialPrompt the server passes us ALREADY contains this in a * STYLE_REFERENCE_BLOCK_MARKER section — but we keep the raw text * here so the editor can label the button "Re-analyze (last run X)" * and so the splice logic below can replace the right block. */ customStyleDescription: string | null; customStyleAnalyzedAt: string | null; /** Free-text note the customer left for the artist (custom-style * orders). Empty string when none. */ artistNote: string; /** Customer revision requests (oldest first). When the order is in * revision_requested, the latest is the change to address — we * pre-fill the Refine box with it and show the list read-only. */ revisions: Array<{ note: string; at: string }>; messages: OrderMessage[]; initialModel: ImageModel; /** Per-model starter prompts. OpenAI gets the full prose image brief; * Gemini gets the compact "ingredient" prompt. The editor keeps both * and swaps the textarea on model switch, remembering edits per model. */ initialPrompts: Record; /** The background colour the customer picked in the Builder (resolved * to label + hex). Null when the style doesn't expose the picker * (cubist/ukiyo-e/etc. carry their own ground) or when it's a custom- * style commission (the upload defines the ground). When set, the * initialPrompts already have a BACKGROUND COLOUR directive baked in * at the top so the AI paints the surround in this hex. */ customerBackground: { hex: string; label: string } | null; /** The lettering choice for "named" portrait variants — the pet's * name + font label. Null when the style doesn't allow lettering, * the customer turned the toggle off, or it's a custom-style * commission. When set, the initialPrompts already have a NAME * LETTERING directive baked in so the AI renders the name. */ customerLettering: { name: string; fontLabel: string } | null; frameConfig: FrameConfig; generations: Generation[]; historyUnavailable: boolean; }; /** Marker that anchors the splice — duplicated from image-gen.ts so * this client component doesn't pull the server-only module in. Must * stay in sync with `STYLE_REFERENCE_BLOCK_MARKER` over there. */ const STYLE_REFERENCE_BLOCK_MARKER = '## STYLE REFERENCE (from your uploaded image)'; /** Splice a freshly-analyzed style description into the existing prompt. * If the prompt already has a STYLE REFERENCE block, replace it in * place (no stacking duplicates on re-analyze). If not, append a fresh * block at the end. */ function spliceStyleDescription(currentPrompt: string, description: string): string { const block = [ STYLE_REFERENCE_BLOCK_MARKER, 'Use the following description (generated by analyzing the uploaded style reference) as your primary guide to the style, especially when generating via OpenAI image-edit which only sees the subject photo.', '', description.trim(), ].join('\n'); const markerIdx = currentPrompt.indexOf(STYLE_REFERENCE_BLOCK_MARKER); if (markerIdx === -1) { const sep = currentPrompt.endsWith('\n\n') ? '' : currentPrompt.endsWith('\n') ? '\n' : '\n\n'; return currentPrompt + sep + block; } // Marker exists — replace from the marker to end-of-string (the // description block is always the last section we add). return currentPrompt.slice(0, markerIdx).trimEnd() + '\n\n' + block; } /** "2m ago" / "just now" — small helper for the Re-analyze label. */ function relativeTime(iso: string | null): string { if (!iso) return ''; const diffMs = Date.now() - new Date(iso).getTime(); const secs = Math.round(diffMs / 1000); if (secs < 30) return 'just now'; if (secs < 60) return `${secs}s ago`; const mins = Math.round(secs / 60); if (mins < 60) return `${mins}m ago`; const hours = Math.round(mins / 60); if (hours < 24) return `${hours}h ago`; const days = Math.round(hours / 24); return `${days}d ago`; } export function AdminEditor(props: Props) { const router = useRouter(); const [model, setModel] = useState(props.initialModel); // Per-model prompts. Each model is prompted differently (OpenAI = full // prose brief, Gemini = compact ingredient prompt), so we keep one // prompt per model and show the active model's. Switching the Model // dropdown swaps the textarea but preserves whatever you'd edited for // each model — switching back restores your edits. const [prompts, setPrompts] = useState>(props.initialPrompts); const prompt = prompts[model]; const [generating, setGenerating] = useState(false); // Refine: free-text tweak ("same but with a red background") applied to // the currently-selected generation. Steers on that render directly. // When the customer has an open revision request, pre-fill it with // their latest note so the admin can refine straight from it. const latestRevision = props.revisions.length > 0 ? props.revisions[props.revisions.length - 1] : null; const [refineText, setRefineText] = useState( props.status === 'revision_requested' ? props.pendingFeedback || latestRevision?.note || '' : '', ); const refineField = useRef(null); const focusRefinement = useRef(false); const [startingRevision, setStartingRevision] = useState(false); const [revisionError, setRevisionError] = useState(null); // Which post-hoc action is in flight on the selected render, so we show // a single loader (not two "Working…" buttons). Null when idle. const [refineAction, setRefineAction] = useState<'refine' | 'finish' | null>(null); const [orderEmailAction, setOrderEmailAction] = useState(null); const [orderEmailFeedback, setOrderEmailFeedback] = useState<{ purpose: MessagePurpose; text: string; warning: boolean } | null>(null); const [drafting, setDrafting] = useState(null); const [draftError, setDraftError] = useState<{ purpose: MessagePurpose; text: string } | null>(null); const [proofNote, setProofNote] = useState(''); const [studioNote, setStudioNote] = useState(''); const [sendingToPrinter, setSendingToPrinter] = useState(false); const [printerError, setPrinterError] = useState(null); const [error, setError] = useState(null); const [selectedId, setSelectedId] = useState(null); const [showAdvanced, setShowAdvanced] = useState(false); const [showReply, setShowReply] = useState(false); const [revisionView, setRevisionView] = useState<'published' | 'draft' | 'print'>('print'); const [revisionAction, setRevisionAction] = useState<'generate' | 'upscale' | null>(null); const [refreshingRevision, refreshRevision] = useTransition(); const revisionBusy = revisionAction !== null || refreshingRevision; const [revisionPreview, setRevisionPreview] = useState<{ id: string; loaded: boolean } | null>(null); const revisionArt = useRef(null); const revealRevisionId = useRef(null); const [sentRevisionId, setSentRevisionId] = useState(null); const selected = props.generations.find(g => g.id === selectedId) ?? props.generations.find(g => g.published) ?? props.generations[0] ?? null; const published = props.generations.find(g => g.id === props.currentProofId) ?? null; const proofRevision = props.proofRevision; const revisionDraft = props.generations.find(g => g.id === proofRevision?.draftId) ?? null; const printUpscale = proofRevision?.printUpscale; const printDraft = props.generations.find(g => g.id === printUpscale?.generationId); const chosenDraft = revisionView === 'draft' ? revisionDraft : printDraft ?? revisionDraft; const revisionPreviewReady = revisionView !== 'published' && !!chosenDraft && revisionPreview?.id === chosenDraft.id && revisionPreview.loaded; const revisionPreviewFailed = revisionView !== 'published' && !!chosenDraft && revisionPreview?.id === chosenDraft.id && !revisionPreview.loaded; const setRevisionPreviewStatus = (id: string, loaded: boolean) => { setRevisionPreview(previous => previous?.id === id && previous.loaded === loaded ? previous : { id, loaded }); }; useEffect(() => { if (!revisionPreviewReady || revisionPreview?.id !== revealRevisionId.current) return; revealRevisionId.current = null; revisionArt.current?.scrollIntoView({ block: 'nearest' }); }, [revisionPreview, revisionPreviewReady]); const showProofWorkbench = !!published && (props.status === 'awaiting_approval' || !!proofRevision); const canRefine = !!selected && PROOF_PUBLISH_STATUSES.includes(props.status); const canStartRevision = props.status === 'awaiting_approval' && !!props.currentProofId; useEffect(() => { if (canRefine && focusRefinement.current) { focusRefinement.current = false; refineField.current?.focus(); } }, [canRefine]); const startRevision = async (note: string) => { const generationId = props.currentProofId; if (!canStartRevision || !generationId || startingRevision) return; setStartingRevision(true); setRevisionError(null); try { const res = await fetch(`/api/admin/orders/${props.orderId}/publish`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ generationId, startRevision: true }), }); const data = await res.json().catch(() => null) as { ok?: boolean; error?: string } | null; if (!res.ok || !data?.ok) { if (res.status === 409) router.refresh(); throw new Error(data?.error ?? 'Could not start the revision.'); } setSelectedId(generationId); setRefineText(note); focusRefinement.current = true; router.refresh(); } catch (error) { setRevisionError(error instanceof Error ? error.message : 'Could not start the revision.'); } finally { setStartingRevision(false); } }; const useCustomerNote = (note: string) => { if (canStartRevision) { void startRevision(note); return; } setRefineText(note); refineField.current?.focus(); }; // Style-analysis state — local mirror of what the server has cached. // analyzedAt is what we render next to "Re-analyze"; description we // only keep to know "has it been analyzed at least once" for the // button label. (The actual text lives in the prompt textarea // already, spliced in via spliceStyleDescription.) const [styleAnalyzedAt, setStyleAnalyzedAt] = useState(props.customStyleAnalyzedAt); const [hasStyleDescription, setHasStyleDescription] = useState(!!props.customStyleDescription); const [analyzing, setAnalyzing] = useState(false); const [analyzeError, setAnalyzeError] = useState(null); const requestGeneration = async (input: { model: ImageModel; prompt?: string; baseGenerationId?: string; finish?: boolean; upscale?: boolean; feedbackAt?: string; replaceDraftId?: string }) => { const attemptId = crypto.randomUUID(); let res: Response; try { res = await fetch(`/api/admin/orders/${props.orderId}/generate`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-generation-attempt': attemptId }, body: JSON.stringify(input), }); } catch { router.refresh(); throw new Error(`The connection ended before the studio received the result. Check History before trying again. Attempt: ${attemptId}`); } const data = await res.json().catch(() => null) as { error?: string; generation?: { id?: string } } | null; if (res.ok && data?.generation?.id) { setSelectedId(data.generation.id); if (input.feedbackAt !== undefined) { revealRevisionId.current = data.generation.id; refreshRevision(() => router.refresh()); } else router.refresh(); return; } if (!data?.error && (res.ok || res.status >= 500)) { router.refresh(); throw new Error(`The studio could not confirm the result. Check History before trying again. Attempt: ${attemptId}`); } if (res.status === 409) router.refresh(); throw new Error(`${data?.error ?? `Generation failed (${res.status}).`} Attempt: ${attemptId}`); }; const generateRevision = async (upscale = false) => { if (!published || !proofRevision || generating || revisionBusy || (upscale && !revisionDraft)) return; setGenerating(true); setRevisionAction(upscale ? 'upscale' : 'generate'); setRevisionError(null); setRevisionView('print'); try { await requestGeneration({ model: resolveImageModel(published.model) ?? OPENAI_IMAGE_MODEL, baseGenerationId: published.id, feedbackAt: proofRevision.feedback.at, replaceDraftId: revisionDraft?.id, upscale, }); } catch (e) { setRevisionError(e instanceof Error ? e.message : 'Could not generate the revision.'); } finally { setRevisionAction(null); setGenerating(false); } }; const onGenerate = async () => { setGenerating(true); setError(null); try { await requestGeneration({ model, prompt }); } catch (e) { setError(e instanceof Error ? e.message : 'Generate failed'); } finally { setGenerating(false); } }; /** Refine the selected generation by steering on it with a free-text * tweak. The reference is that render's clean file (handled server- * side); we just send the raw instruction + which render to base on. * Use the current version of the engine that produced the pixels. */ const onRefine = async () => { if (!selected || !refineText.trim()) return; const refineModel = resolveImageModel(selected.model) ?? OPENAI_IMAGE_MODEL; setGenerating(true); setRefineAction('refine'); setError(null); try { await requestGeneration({ model: refineModel, prompt: refineText.trim(), baseGenerationId: selected.id }); setRefineText(''); } catch (e) { setError(e instanceof Error ? e.message : 'Refine failed'); } finally { setGenerating(false); setRefineAction(null); } }; /** Re-render the selected proof with the current OpenAI image model. */ const onFinish = async () => { if (!selected) return; setGenerating(true); setRefineAction('finish'); setError(null); try { await requestGeneration({ model: OPENAI_IMAGE_MODEL, baseGenerationId: selected.id, finish: true }); } catch (e) { setError(e instanceof Error ? e.message : 'Finish failed'); } finally { setGenerating(false); setRefineAction(null); } }; const sendOrderUpdate = async (generationId?: string, sendRevision = false, resumeReview = false) => { const purpose = generationId ? 'proof' : 'message'; const note = sendRevision ? '' : (generationId ? proofNote : studioNote).trim(); if (sendRevision && (revisionBusy || !revisionPreviewReady)) return; if (resumeReview && (!proofRevision || revisionBusy || generating)) return; if (drafting || orderEmailAction || (!generationId && !note)) return; setOrderEmailAction(purpose); setOrderEmailFeedback(null); setDraftError(null); try { const res = await fetch(`/api/admin/orders/${props.orderId}/publish`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ generationId, note, sendRevision, ...(resumeReview && proofRevision ? { resumeProof: { generationId: proofRevision.baseGenerationId, feedbackAt: proofRevision.feedback.at } } : {}), }), }); const data = await res.json().catch(() => null) as { error?: string; emailSent?: boolean } | null; if (!res.ok) { if (res.status === 409) router.refresh(); throw new Error(data?.error ?? `Could not save your update (${res.status}).`); } if (generationId) setProofNote(''); else { setStudioNote(''); setShowReply(false); } if (generationId) { setRevisionView('print'); if (sendRevision) setSentRevisionId(generationId); } setOrderEmailFeedback(data?.emailSent ? { purpose, text: resumeReview ? 'Reply sent. The same proof is back in review.' : `${sendRevision ? 'Revised proof published' : generationId ? 'Proof published' : 'Message saved'} and sent by email.`, warning: false } : { purpose, text: resumeReview ? 'Reply saved and proof review resumed. The email could not be sent.' : 'The update was saved on the order, but the email could not be sent.', warning: true }); router.refresh(); } catch (e) { setOrderEmailFeedback({ purpose, text: e instanceof Error ? e.message : 'Could not save your update.', warning: true }); } finally { setOrderEmailAction(null); } }; const generateReply = async (purpose: MessagePurpose, generationId?: string) => { if (drafting || orderEmailAction) return; const setNote = purpose === 'proof' ? setProofNote : setStudioNote; setDrafting(purpose); setDraftError(null); setOrderEmailFeedback(null); try { const res = await fetch(`/api/admin/orders/${props.orderId}/draft-reply`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ purpose, generationId }), }); const data = await res.json().catch(() => null) as { draft?: string; error?: string } | null; if (!res.ok || !data?.draft) { if (res.status === 409) router.refresh(); throw new Error(data?.error ?? 'Could not generate a draft.'); } const draft = data.draft; setNote(current => current.trim() ? current : draft); } catch (e) { setDraftError({ purpose, text: e instanceof Error ? e.message : 'Could not generate a draft.' }); } finally { setDrafting(null); } }; const onAnalyzeStyle = async () => { setAnalyzing(true); setAnalyzeError(null); try { const res = await fetch(`/api/admin/orders/${props.orderId}/analyze-style`, { method: 'POST', }); const data = await res.json().catch(() => null) as { description?: string; analyzedAt?: string; error?: string; } | null; if (!res.ok || !data?.description) { throw new Error(data?.error ?? `Analyze failed (${res.status})`); } // Splice the freshly-described style into the OpenAI prompt only — // the description exists so OpenAI's single-image /images/edits can // mimic a style it can't see. Gemini sees the style image directly // and doesn't need it. Idempotent — re-running swaps the block in // place. setPrompts((p) => ({ ...p, [OPENAI_IMAGE_MODEL]: spliceStyleDescription(p[OPENAI_IMAGE_MODEL], data.description!), })); setStyleAnalyzedAt(data.analyzedAt ?? new Date().toISOString()); setHasStyleDescription(true); } catch (e) { setAnalyzeError(e instanceof Error ? e.message : 'Analyze failed'); } finally { setAnalyzing(false); } }; const onSendToPrinter = async () => { if (!confirm('Send this order to Prodigi? Once printed, it ships — no taking it back. The clean print file + shipping address should both be sanity-checked first.')) { return; } setSendingToPrinter(true); setPrinterError(null); try { const res = await fetch(`/api/admin/orders/${props.orderId}/send-to-printer`, { method: 'POST', }); if (!res.ok) { const data = await res.json().catch(() => null) as { error?: string } | null; throw new Error(data?.error ?? `Send to printer failed (${res.status})`); } router.refresh(); } catch (e) { setPrinterError(e instanceof Error ? e.message : 'Send to printer failed'); } finally { setSendingToPrinter(false); } }; return (
{showProofWorkbench && published && (() => { const sentRevision = props.sentRevisions.findLast(revision => revision.generationId === published.id); const previousProof = props.generations.find(g => g.id === sentRevision?.baseGenerationId); const compareFrom = revisionDraft ? published : !proofRevision ? previousProof : undefined; const preview = revisionView === 'published' && compareFrom ? compareFrom : chosenDraft ?? published; const previewLabel = preview === printDraft ? 'Upscaled draft' : preview === revisionDraft ? 'Revision draft' : preview === published ? 'Published proof' : 'Previous proof'; const dimensions = printDraft ? printUpscale : sentRevision?.printUpscale; const publishedNote = props.messages.findLast(message => message.kind === 'proof' && message.generationId === published.id); const previousPublishedNote = previousProof && props.messages.findLast(message => message.kind === 'proof' && message.generationId === previousProof.id); const previewNote = previewLabel === 'Previous proof' ? previousPublishedNote : publishedNote; const feedback = proofRevision?.feedback ?? sentRevision?.feedback; const conversation = props.messages.filter(message => message !== publishedNote); return (
{compareFrom && (
{printDraft && }
)} setRevisionPreviewStatus(preview.id, true) : undefined} onImageError={preview === revisionDraft || preview === printDraft ? () => setRevisionPreviewStatus(preview.id, false) : undefined} />

{previewLabel} · {sizeLabel(props.frameConfig.productId, props.frameConfig.size, props.frameConfig.orientation)}

{revisionDraft ? 'Review revision draft' : 'Proof conversation'}

{revisionDraft ? 'This draft is based on the published proof. Only the studio can see it.' : proofRevision ? 'The customer requested changes. This proof is open for revision.' : sentRevision ? 'Revised proof sent. Awaiting customer review.' : 'The customer can approve this proof or ask for changes.'}

{previewNote &&
{previewLabel === 'Previous proof' ? 'Your previous proof note' : 'Your published note'}

{previewNote.note}

} {feedback && (
{proofRevision ? 'What the customer said' : 'Customer feedback for this revision'}
{feedback.note}
)} {revisionBusy && (
{revisionAction === 'upscale' ? 'Upscaling for print…' : revisionAction === 'generate' ? 'Generating revision…' : 'Loading updated proof…'} {revisionAction && {revisionAction === 'upscale' ? 'Enlarging and verifying the print file.' : 'Applying the customer’s feedback. This can take a minute or two.'}}
)} {revisionPreviewFailed && (

The revision was saved, but its image couldn’t load. Reload this page or try another revision.

)} {dimensions &&

Print resolution {dimensions.original.width} × {dimensions.original.height} px → {dimensions.upscaled.width} × {dimensions.upscaled.height} px

} {chosenDraft ? (
{!printDraft && }
{!revisionPreviewFailed &&

{revisionView === 'published' ? 'Select a draft to send it.' : !revisionPreviewReady ? 'Loading the revision preview…' : 'Publishes the draft to the same proof page and emails the customer.'}

}
) : proofRevision ? (

Applies this feedback to the published proof and creates a draft for you to review.

) : null} {revisionError &&

{revisionError}

} {orderEmailFeedback &&

{orderEmailFeedback.text}

} {!orderEmailFeedback && sentRevisionId === published.id &&

Revised proof sent.

} {showReply && (
{ event.preventDefault(); void sendOrderUpdate(undefined, false, !!proofRevision); }}>